package router

import (
	"errors"

	"gitea.in/wx-rdc/service-base/internal/pkg/core"
	"gitea.in/wx-rdc/service-base/internal/repository/mysql"

	"go.uber.org/zap"
)

type resource struct {
	mux        core.Mux
	logger     *zap.Logger
	cronLogger *zap.Logger
	db         mysql.Repo
}

type Server struct {
	Mux core.Mux
	Db  mysql.Repo
}

func NewHTTPServer(logger *zap.Logger, cronLogger *zap.Logger) (*Server, error) {
	if logger == nil {
		return nil, errors.New("logger required")
	}

	r := new(resource)
	r.logger = logger
	r.cronLogger = cronLogger

	// openBrowserUri := configs.ProjectDomain + configs.ProjectPort

	// _, ok := file.IsExists(configs.ProjectInstallMark)
	// if !ok { // 未安装
	// 	openBrowserUri += "/install"
	// } else { // 已安装

	// 初始化 DB
	dbRepo, err := mysql.New()
	if err != nil {
		logger.Fatal("new db err", zap.Error(err))
	}
	r.db = dbRepo

	// auto migrate

	mux, err := core.New(logger,
		// core.WithEnableOpenBrowser(openBrowserUri),
		core.WithEnableCors(),
		core.WithEnableRate(),
		core.WithDisableTrace(),
	)

	if err != nil {
		panic(err)
	}

	r.mux = mux

	// 设置 Render 路由
	// setRenderRouter(r)

	// 设置 API 路由
	setApiRouter(r)

	// 设置 GraphQL 路由
	// setGraphQLRouter(r)

	// 设置 Socket 路由
	// setSocketRouter(r)

	s := new(Server)
	s.Mux = mux
	s.Db = r.db

	return s, nil
}
